package com.ebt.m.cloud.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ebt.m.R;
import com.ebt.m.cloud.EbtVideoActivity;
import com.ebt.m.cloud.bean.MyBusinessInfLocal;
import com.ebt.m.cloud.callback.MyDownloadListener;
import com.ebt.m.cloud.db.DBController;
import com.ebt.m.cloud.downloader.DownloadService;
import com.ebt.m.cloud.downloader.callback.DownloadManager;
import com.ebt.m.cloud.downloader.domain.DownloadInfo;
import com.ebt.m.cloud.event.DownloadStatusChanged;
import com.ebt.m.cloud.util.FileUtil;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.SoftReference;
import java.sql.SQLException;
import java.util.HashMap;


public class DownloadAdapter extends BaseRecyclerViewAdapter<DownloadInfo, DownloadAdapter.ViewHolder> {

    private DBController dbController;
    private DownloadManager downloadManager;
    private boolean isEdit;
    private HashMap<Integer, Boolean> selected = new HashMap();

    public HashMap<Integer, Boolean> getSelected() {
        return selected;
    }

    public DownloadAdapter(Context context) {
        super(context);
        try {
            dbController = DBController.getInstance();
            downloadManager = DownloadService.getDownloadManager(context);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void setEditMode(boolean isEdit) {
        this.isEdit = isEdit;
        notifyDataSetChanged();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new DownloadAdapter.ViewHolder(LayoutInflater.from(context).inflate(R.layout.cache_item, parent, false));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        DownloadInfo data = getItemData(position);
        try {
            MyBusinessInfLocal myDownloadInfoById = dbController.findMyDownloadInfoById((long) data.getUri().hashCode());
            if (myDownloadInfoById != null) {
                holder.bindBaseInfo(myDownloadInfoById);
                data.setName(myDownloadInfoById.getName());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        holder.bindData(data, position, context);
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private ImageView iv_icon;
        private CheckBox checkBox;
        private TextView tv_size;
        private TextView tv_status;
        private ProgressBar pb;
        private TextView tv_name;
        private ImageView bt_action;
        private ImageView ic_video_play;
        private DownloadInfo downloadInfo;

        public ViewHolder(View view) {
            super(view);
            checkBox = (CheckBox) view.findViewById(R.id.checkbox);
            iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
            ic_video_play = (ImageView) view.findViewById(R.id.ic_video_play);
            tv_size = (TextView) view.findViewById(R.id.tv_size);
            tv_status = (TextView) view.findViewById(R.id.tv_status);
            pb = (ProgressBar) view.findViewById(R.id.pb);
            tv_name = (TextView) view.findViewById(R.id.tv_name);
            bt_action = (ImageView) view.findViewById(R.id.bt_action);
        }

        public void bindData(final DownloadInfo data, int position, final Context context) {
            downloadInfo = data;
            if (downloadInfo.getStatus() == DownloadInfo.STATUS_COMPLETED) {
                itemView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
//                            FileUtils.openFile(context, new File(downloadInfo.getPath()));
//                            String url = "http://m.test.e-baotong.cn/zyCloud/zycCourse?courseId=" + data.getSourceId() + "&from=cache";
//                            Intent webIntent = new Intent(context, WebBaseActivity.class);
//                            Bundle bundle = new Bundle();
//                            bundle.putString(WebBaseActivity.WEB_TYPE_TITLE, data.getName());
//                            bundle.putBoolean(WebBaseActivity.WEB_TYPE_HIDE_TOOLBAR, false);
//                            bundle.putString(WebBaseActivity.WEB_TYPE_LINK, url);
//                            bundle.putInt(WebBaseActivity.WEB_TYPE_FRAGMENT, WebBaseActivity.FRAGMENT_4OLD_BASE);
//                            webIntent.putExtras(bundle);
//                            context.startActivity(webIntent);
                            //20181121打开自己的视频播放器播放视频
                            Intent intent = new Intent(context, EbtVideoActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("video_path", downloadInfo.getPath());
                            String title = downloadInfo.getName();
                            if (title != null && title.contains(".")) {
                                title = title.substring(0, title.lastIndexOf("."));
                            }
                            bundle.putString("title", title);
                            intent.putExtras(bundle);
                            context.startActivity(intent);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            if (downloadInfo != null) {
                downloadInfo.setDownloadListener(new MyDownloadListener(new SoftReference(DownloadAdapter.ViewHolder.this)) {
                    @Override
                    public void onRefresh() {
                        notifyDownloadStatus();
                        if (getUserTag() != null && getUserTag().get() != null) {
                            DownloadAdapter.ViewHolder viewHolder = (DownloadAdapter.ViewHolder) getUserTag().get();
                            viewHolder.refresh();
                        }
                    }
                });

            }
            if (selected.get(data.getId()) == null) {
                checkBox.setChecked(false);
            } else {
                checkBox.setChecked(selected.get(data.getId()));
            }
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        selected.put(data.getId(), true);
                    }
                }
            });
            refresh();
//      Download button
            bt_action.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (downloadInfo != null) {

                        switch (downloadInfo.getStatus()) {
                            case DownloadInfo.STATUS_NONE:
                            case DownloadInfo.STATUS_PAUSED:
                            case DownloadInfo.STATUS_ERROR:

                                //resume downloadInfo
                                downloadManager.resume(downloadInfo);
                                break;

                            case DownloadInfo.STATUS_DOWNLOADING:
                            case DownloadInfo.STATUS_PREPARE_DOWNLOAD:
                            case DownloadInfo.STATUS_WAIT:
                                //pause downloadInfo
                                downloadManager.pause(downloadInfo);
                                break;
                            case DownloadInfo.STATUS_COMPLETED:
                                downloadManager.remove(downloadInfo);
                                break;
                        }
                    }
                }
            });

        }

        private void refresh() {
            pb.setVisibility(View.VISIBLE);
            tv_size.setVisibility(View.VISIBLE);
            ic_video_play.setVisibility(View.GONE);
            bt_action.setVisibility(View.VISIBLE);
            if (isEdit) {
                checkBox.setVisibility(View.VISIBLE);
            } else {
                checkBox.setVisibility(View.GONE);
            }
            if (downloadInfo == null) {
                tv_size.setText("");
                pb.setProgress(0);
                bt_action.setImageResource(R.drawable.ic_play);
                tv_status.setText("无缓存信息");
            } else {
                switch (downloadInfo.getStatus()) {
                    case DownloadInfo.STATUS_NONE:
                        bt_action.setImageResource(R.drawable.ic_play);
                        tv_status.setText("无缓存信息");
                        break;
                    case DownloadInfo.STATUS_PAUSED:
                    case DownloadInfo.STATUS_ERROR:
                        bt_action.setImageResource(R.drawable.ic_play);
                        tv_status.setText("已暂停");
                        try {
                            pb.setProgress((int) (downloadInfo.getProgress() * 100.0 / downloadInfo.getSize()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        tv_size.setText(FileUtil.formatFileSize(downloadInfo.getProgress()) + "/" + FileUtil
                                .formatFileSize(downloadInfo.getSize()));
                        break;

                    case DownloadInfo.STATUS_DOWNLOADING:
                    case DownloadInfo.STATUS_PREPARE_DOWNLOAD:
                        bt_action.setImageResource(R.drawable.ic_pause);
                        try {
                            pb.setProgress((int) (downloadInfo.getProgress() * 100.0 / downloadInfo.getSize()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        tv_size.setText(FileUtil.formatFileSize(downloadInfo.getProgress()) + "/" + FileUtil
                                .formatFileSize(downloadInfo.getSize()));
                        tv_status.setText("缓存中...");
                        break;
                    case DownloadInfo.STATUS_COMPLETED:
                        bt_action.setVisibility(View.GONE);
                        try {
                            pb.setVisibility(View.INVISIBLE);
                            tv_size.setVisibility(View.GONE);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
//                        tv_size.setText(FileUtil.formatFileSize(downloadInfo.getProgress()) + "/" + FileUtil
//                                .formatFileSize(downloadInfo.getSize()));
                        tv_status.setText("已缓存");
                        ic_video_play.setVisibility(View.VISIBLE);
                        publishDownloadSuccessStatus();
                        break;
                    case DownloadInfo.STATUS_REMOVED:
                        tv_size.setText("");
                        pb.setProgress(0);
                        bt_action.setImageResource(R.drawable.ic_play);
                        tv_status.setText("无下载信息");

                        publishDownloadSuccessStatus();
                    case DownloadInfo.STATUS_WAIT:
                        tv_size.setText("");
                        pb.setProgress(0);
                        bt_action.setImageResource(R.drawable.ic_pause);
                        tv_status.setText("等待缓存");
                        break;
                }

            }
        }

        private void publishDownloadSuccessStatus() {
            //publish download success info.
            EventBus.getDefault().post(new DownloadStatusChanged(downloadInfo));
        }

        public void bindBaseInfo(MyBusinessInfLocal myBusinessInfLocal) {
            Glide.with(context).load(myBusinessInfLocal.getIcon()).into(iv_icon);
            String name = myBusinessInfLocal.getName();
            if (!TextUtils.isEmpty(name) && name.contains(".")) {
                name = name.substring(0, name.lastIndexOf("."));
            }
            tv_name.setText(name);
        }

        private void notifyDownloadStatus() {
            if (downloadInfo.getStatus() == DownloadInfo.STATUS_REMOVED) {
                try {
                    dbController.deleteMyDownloadInfo(downloadInfo.getUri().hashCode());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
